import 'dart:convert';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../EcyRouter.dart';
import '../../../constant/color_constant.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyLogger.dart';
import '../../../ecycommon/utils/EcyUserUtil.dart';
import '../../../model/EcyApiCommonResponse.dart';

class EcyLogOffPage extends StatefulWidget {
  const EcyLogOffPage({required super.key});

  @override
  State<StatefulWidget> createState() => _EcyLogOffPageState();
}

class _EcyLogOffPageState extends State<EcyLogOffPage>
    with SingleTickerProviderStateMixin {
  _EcyLogOffPageState();

  final ScrollController _scrollController = ScrollController();
  bool checked = false;
  bool loadingFlag = false;
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat();
  }

  Future<void> _logOffAccount() async {
    if (loadingFlag) {
      return;
    }

    setState(() {
      loadingFlag = true;
    });

    try {
      var loginFlag = await EcyUserUtil.logined();
      if (loginFlag) {
        var response = await EcyRequestbasemanager()
            .post('/app/api/app/user/unregister', {});
        if (response != null) {
          var commonResponse =
              EcyApiCommonResponse.fromJson(response, (response) => json);
          if (commonResponse.code != 0 && commonResponse.code != 200) {
            EasyLoading.showToast(commonResponse.msg ?? "请稍后再试",
                duration: const Duration(seconds: 2));
            return;
          }

          EcyUserUtil.clearUserInfo();
          EcyRouter.popAndPushNamed(context, '/', {});
        }
      } else {
        EasyLoading.showToast("请先登录", duration: const Duration(seconds: 1));
      }
    } catch (e) {
      EcyLogger.log("注销账号失败$e");
    } finally {
      loadingFlag = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        leadingWidth: 50.w,
        leading: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            EcyRouter.pop(context, "");
          },
          child: Align(
            alignment: Alignment.centerRight,
            child: Image.asset(
              "assets/images/ic_back.png",
              width: 30.w,
            ),
          ),
        ),
        titleSpacing: 0,
        title: const Text('账号注销',
            style: TextStyle(
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w700,
                fontSize: 16,
                color: Color(0xFF262626))),
        centerTitle: true,
      ),
      body: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          color: const Color(0xFFF5F5F5),
          child: SingleChildScrollView(
            controller: _scrollController,
            child: Padding(
              padding: const EdgeInsets.all(8),
              child: Column(
                children: [
                  Padding(
                    padding: const EdgeInsets.all(8),
                    child: Text(
                      '一旦您选择注销账号，您在有谷气的个人身份信息、账号信息等所有会员'
                      '权益都将被永久清空且无法恢复。同时，您在有谷气的所有交易记录也'
                      '将被彻底清除。',
                      textAlign: TextAlign.justify,
                      style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w700,
                          fontSize: 16.sp,
                          color: const Color(0xFFa0522d)),
                    ),
                  ),
                  SizedBox(
                      width: MediaQuery.of(context).size.width,
                      child: Card(
                        color: Colors.white,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: const EdgeInsets.all(10),
                              child: Container(
                                width: double.infinity,
                                color: const Color(0xFFFFFFFF),
                                child: Column(
                                  children: [
                                    Text(
                                      "您在有谷气的所有交易记录也将被"
                                      "彻底清除。账号近期不存在交易：您的账户无未完成"
                                      "订单、无已完成但存在售后交易、无待寄售商品等。"
                                      "账号不存在进行中的违规记录：您的账号不存在"
                                      "正在进行中的违规处罚或限权记录。账号相关财产权"
                                      "益已结清",
                                      textAlign: TextAlign.justify,
                                      style: TextStyle(
                                          fontFamily: "PingFang SC",
                                          fontWeight: FontWeight.w500,
                                          fontSize: 16.sp,
                                          color: const Color(0xFF8C8C8C)),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      )),
                  SizedBox(
                      width: MediaQuery.of(context).size.width,
                      child: Card(
                        color: Colors.white,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: const EdgeInsets.all(10),
                              child: Container(
                                width: double.infinity,
                                color: const Color(0xFFFFFFFF),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    const Text(
                                      "注意",
                                      style: TextStyle(
                                          fontFamily: "PingFang SC",
                                          fontWeight: FontWeight.w700,
                                          fontSize: 16,
                                          color: Color(0xFF262626)),
                                    ),
                                    Text(
                                      "有谷气账号注销：请确保所有交易已完结且无纠纷，账"
                                      "号注销后因历史交易可能产生的退换货、维权相关"
                                      "的资金退回等权益将视作自动放弃。",
                                      textAlign: TextAlign.justify,
                                      style: TextStyle(
                                          fontFamily: "PingFang SC",
                                          fontWeight: FontWeight.w500,
                                          fontSize: 16.sp,
                                          color: const Color(0xFF8C8C8C)),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      )),
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 12),
                    child: Align(
                      alignment: Alignment.center,
                      child: Wrap(
                        direction: Axis.horizontal,
                        spacing: 0,
                        children: [
                          GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () => {
                              setState(() {
                                checked = !checked;
                              }),
                            },
                            child: Image(
                                image: AssetImage(checked
                                    ? 'assets/images/login_checked.png'
                                    : 'assets/images/login_unchecked.png'),
                                width: 22.w,
                                height: 22.w),
                          ),
                          GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () {},
                            child: Padding(
                              padding: const EdgeInsets.only(top: 3),
                              child: RichText(
                                text: TextSpan(
                                  children: [
                                    TextSpan(
                                      text: ' 已阅读并同意',
                                      style: TextStyle(
                                          color: const Color.fromARGB(
                                              255, 140, 140, 140),
                                          fontSize: 12.sp),
                                    ),
                                    TextSpan(
                                        recognizer: TapGestureRecognizer()
                                          ..onTap = () {
                                            EcyRouter.push(context,
                                                EcyRouter.privacyPolicyPage, {
                                              "url":
                                                  "https://www.goodsqi.com/agreement/logout/logout.html",
                                              "title": "注销提醒"
                                            });
                                          },
                                        text: '《有谷气账号注销重要提醒》',
                                        style: TextStyle(
                                            color: ColorConstant.CommonColor,
                                            fontSize: 12.sp)),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Expanded(
                        flex: 1,
                        child: Container(
                          height: 45.w,
                          padding: const EdgeInsets.symmetric(horizontal: 4),
                          child: TextButton(
                            onPressed: () async {
                              if (!checked) {
                                EasyLoading.showToast("请先勾选协议",
                                    toastPosition:
                                        EasyLoadingToastPosition.center,
                                    duration: const Duration(seconds: 2));
                                return;
                              }
                              //弹出对话框并等待其关闭
                              bool? delete =
                                await showConfirmDialog('确定需要注销该账号吗？');
                              if (delete != null && delete) {
                                _logOffAccount();
                              }
                            },
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                              backgroundColor:
                                  WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                              foregroundColor:
                                  WidgetStatePropertyAll(Colors.white),
                            ),
                            child:
                            Stack(children: [
                              SizedBox(
                                height: 45.w,
                                width: 45.w,
                                child: Align(
                                  alignment: Alignment.center,
                                  child: Transform.translate(
                                    offset: const Offset(-35.0, 2.0),
                                    child: loadingFlag
                                        ? RotationTransition(
                                      // 使用 RotationTransition 实现旋转
                                      alignment: Alignment.center,
                                      turns: Tween(begin: 0.0, end: 2.0)
                                          .animate(_controller),
                                      child: Image.asset(
                                          width: 30.w,
                                          height: 30.w,
                                          alignment: Alignment.center,
                                          "assets/images/loading/loading-white.png"),
                                    )
                                        : null,
                                  ),
                                ),
                              ),
                              SizedBox(
                                  height: 45.w,
                                  width: 45.w,
                                  child: Align(
                                    alignment: Alignment.center,
                                    child: Text('确定',
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontFamily: "PingFang SC",
                                            fontWeight: FontWeight.w500,
                                            fontSize: 18.sp,
                                            color: ColorConstant.White)),
                                  )),
                            ])
                          ),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          )),
    );
  }

  // 弹出对话框
  Future<bool?> showConfirmDialog(String content) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          // title: const Text(''),
          contentPadding: const EdgeInsets.all(0),
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          content: SizedBox(
            height: 130,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 20, bottom: 30),
                  child: Text(
                    content,
                    style: const TextStyle(fontSize: 18),
                  ),
                ),
                const Divider(height: 0, color: Color(0XFFdcdcdc)),
                SizedBox(
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: DecoratedBox(
                          decoration: const BoxDecoration(
                              border: Border(
                                right: BorderSide(
                                  width: 1.0,
                                  color: Color(0XFFdcdcdc),
                                ),
                              )
                          ),
                          child: TextButton(
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                            ),
                            child: const Text('取消', style: TextStyle(fontSize: 18, color: Colors.black),),
                            onPressed: () => Navigator.of(context).pop(), // 关闭对话框
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: TextButton(
                          child: const Text('确定', style: TextStyle(fontSize: 18, color: Color(0xFFEA4B9B)),),
                          onPressed: () {
                            //关闭对话框并返回true
                            Navigator.of(context).pop(true);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actionsAlignment: MainAxisAlignment.spaceAround,
          actionsPadding: const EdgeInsets.all(0),
        );
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
    _controller.dispose();
  }

  @override
  void deactivate() {
    super.deactivate();
  }

}
